<template>
  <section class="todoapp">
    <todo-header @addList="addList"></todo-header>
    <todo-body :list="renderList"
               @changeFlag="changeFlag"
               @delList="delList"
               @changeAll="changeAll">
               </todo-body>
    <todo-footer :sum="sum"
                 :showClearBtn="showClearBtn"
                 @change="changeType"
                 @delAll="delAll"></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoBody from "./components/TodoBody.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoBody,
    TodoFooter,
  },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('list'))||[
        { id: 1, value: '读万卷书', flag: false },
        { id: 2, value: '行万里路', flag: true },
        { id: 3, value: '做万件事', flag: false },
      ],
      type: 'all'
    }
  },
  methods: {
    addList (value) {
      this.list = [...this.list, {
        flag: false,
        id: +new Date(),
        value
      }]
    },
    changeFlag (id, flag) {
      this.list.forEach(item => {
        if (item.id === id) item.flag = flag
      })
    },
    delList (id) {
      const event = this.list.find(item => item.id === id)
      if (!event.flag) return alert('未完成没法删')

      this.list = this.list.filter(item => item.id !== id)
    },
    delAll () {
      this.list = this.list.filter(item => !item.flag)
    },
    changeType (value) {
      this.type = value
    },
    changeAll(flag){
      this.list=this.list.forEach(item=>item.flag=flag)
    }
  },
  computed: {
    sum () {
      return this.list.filter(item => !item.flag).length
    },
    showClearBtn () {
      return this.list.some(item => item.flag)
    },
    renderList () {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item => !item.flag)
        case 'completed':
          return this.list.filter(item => item.flag)
        default:
          return this.list
      }
    }
  },
  watch:{
    list:{
      immediate:true,
      deep:true,
      handler(newVal){
        localStorage.setItem('list',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
